from rest_framework import serializers

from apps.lookups.calendars.models import CalendarType
from bases.serializers import APIModelSerializer
from django.utils.translation import gettext_lazy as _


class CalendarTypeSerializer(APIModelSerializer):
    calendar_type = serializers.CharField(allow_null=True, allow_blank=True, required=False)
    calendar_name = serializers.CharField(allow_null=True, allow_blank=True, required=False)
    holiday = serializers.CharField(allow_null=True, allow_blank=True, required=False)
    exist_calendar = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = CalendarType
        fields = '__all__'

    def get_exist_calendar(self, obj):
        return obj.exist_calendar

    def validate(self, attrs):
        calendar_type = attrs.get('calendar_type')
        if self.request.method.lower() == 'post':
            if CalendarType.objects.filter(calendar_type__exact=calendar_type).exists():
                # Translators: 在系统中已经存在
                self.handle_validation('calendar_type', _('it already exists in the system'))
        else:
            if CalendarType.objects.exclude(pk=self.instance.pk).filter(calendar_type__exact=calendar_type).exists():
                self.handle_validation('calendar_type', _('it already exists in the system'))

        return super().validate(attrs)
